<template>
  <Card class="card">
    <Form :model="formItem" :label-width="80">
      <FormItem label="文件上传" style="text-align:left">
        <span>{{fileName}}</span>
        <upLoadBtn idName="excel-upload" @fileUpload="fileUpload" :fileChangeLoading="fileChangeLoading" color="success" size="small" accept=".xls,.xlsx" style="display:inline" />
      </FormItem>
      <FormItem label="KEY Name" prop="key">
        <Input type="text" v-model="formItem.key" />
      </FormItem>
      <FormItem label="Value Name" prop="value">
        <Input type="text" v-model="formItem.value" />
      </FormItem>
      <FormItem>
        <Button type="primary" @click="handleSubmit" :loading="fileChangeLoading">提交</Button>
      </FormItem>
    </Form>
    <Alert v-show="jsonData" style="text-align:left;">
      <pre>{{jsonData}}</pre>
    </Alert>
  </Card>
</template>

<script>
import { upLoadExl } from 'api'
import upLoadBtn from 'components/upLoadBtn'
export default {
  name: 'home',
  data() {
    return {
      formItem: {
        key: '',
        value: ''
      },
      fileChangeLoading: false,
      file: null,
      fileName: '',
      jsonData: ''
    }
  },
  components: {
    upLoadBtn
  },
  methods: {
    async handleSubmit() {
      if (this.file) {
        this.fileChangeLoading = true
        let formData = new FormData()
        formData.append('file', this.file)
        this.formItem.key && formData.append('key', this.formItem.key)
        this.formItem.value && formData.append('value', this.formItem.value)
        const res = await upLoadExl(formData);
        if (res.code == 0) {
          this.jsonData = JSON.stringify(res.data).replace(/{/g, '').replace(/}/g, '').replace(/\[/g, '{').replace(/\]/g, '}').replace(/","/g, '",\n\r"')
        } else {
          this.$Message.error(res.msg);
        }
        this.fileChangeLoading = false
      } else {
        this.$Message.error('没传文件提交个毛线！');
      }
    },
    fileUpload(itemFile) {
      this.file = itemFile
      this.fileName = itemFile.name
    },
  }
}
</script>
<style lang="stylus">
  .card
    width 500px
    margin 10vh auto
    padding-top 30px
</style>

